package binarytree;

import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/21 17:51
 * https://leetcode-cn.com/problems/path-sum/
 */
public class HasPathSum {

    static class TreeNode {
        int val;

        TreeNode left;

        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 递归
     * @param root
     * @param targetSum
     * @return
     */
    public static boolean hasPathSum(TreeNode root, int targetSum) {
        int sum = 0;
        if (root == null) {
            return false;
        }
        return traversal(root, sum, targetSum);
    }

    public static boolean traversal(TreeNode root, int paths, int targetSum) {
        paths += root.val;
        if (root.left == null && root.right == null && paths == targetSum) {
            return true;
        }
        boolean left = false;
        boolean right = false;
        if (root.left != null) {
            left = traversal(root.left, paths, targetSum);
        }
        if (root.right != null) {
            right = traversal(root.right, paths, targetSum);
        }
        return left || right;
    }

    /**
     * 迭代 占空间。仍需要存储经过的每个结点
     * @param root
     * @param targetSum
     * @return
     */
    public static boolean hasPathSum1(TreeNode root, int targetSum) {
        //栈，存放结点
        Stack<TreeNode> stack = new Stack<>();
        //栈，存放经过结点值的总和
        Stack<Integer> paths = new Stack<>();
        if (root != null) {
            stack.push(root);
            paths.push(root.val);
        }
        while (!stack.isEmpty()) {
            TreeNode pop = stack.pop();
            Integer value = paths.pop();
            if (pop.left == null && pop.right == null ) {
                if (value == targetSum) {
                    return true;
                }
                continue;
            }
            if (pop.right != null) {
                stack.push(pop.right);
                paths.push(value + pop.right.val);
            }
            if (pop.left != null) {
                stack.push(pop.left);
                paths.push(value + pop.left.val);
            }
        }
        return false;
    }


    public static void main(String[] args) {
        TreeNode root = new TreeNode(0);
        TreeNode left = new TreeNode(1);
        TreeNode right = new TreeNode(1);
        root.left = left;
        root.right = right;
        boolean b = hasPathSum(root, 0);
        System.out.println(b);
    }
}
